module(..., package.seeall)
require "pins"
require "common"
BL = pins.setup(4, 0)
BL(0)
isSleep = true
function sleep()
    if isSleep then return end
    pm.sleep("lcd_up")
    isSleep = true
    disp.sleep(1)
    BL(0)
end

function wake(f)
    if not isSleep then return end
    pm.wake("lcd_up")
    isSleep = nil
    disp.sleep(0)
    if not f then
        page.update()
    end
    BL(1)
    io.unmount(io.SDCARD)
    io.mount(io.SDCARD)
end
--rgb值转rgb565
function rgb(r,g,b)
    return (r-r%8)/8*2048 + (g-g%4)/4*32 + (b-b%8)/8
end

--放置文字，自动转码
function text(s,x,y,r,g,b)
    if r and g and b then
        disp.setcolor(rgb(r,g,b))
    end
    disp.puttext(common.utf8ToGb2312(s),x,y)
end
--居中显示文字
function putStringCenter(s,x,y,r,g,b)
    local str = common.utf8ToGb2312(s)
    text(s,x-str:len()*((CHAR_WIDTH-CHAR_WIDTH%2)/2),y,r,g,b)
end
--靠右显示文字
function putStringRight(s,x,y,r,g,b)
    local str = common.utf8ToGb2312(s)
    text(s,x-str:len()*CHAR_WIDTH,y,r,g,b)
end

--快速计算y
function gety(l)
    return l*CHAR_WIDTH*2
end

--快速计算x
function getx(l)
    return l*CHAR_WIDTH
end
sys.taskInit(function()
    sys.waitUntil("LCD_INIT")
    wake(1)
    CHAR_WIDTH = 16
    disp.setfontheight(32)
    disp.clear()
    for i=1,51 do
        local c = i*5
        putStringCenter("欢迎使用",120,90,c,c,c)
        putStringCenter("X Magic Box",120,130,c,c,c)
        disp.update()
    end
    sys.wait(1000)
    disp.clear()
    -- CHAR_WIDTH = 16
    -- disp.setfontheight(16)

    
    text("联网计算机你好:",5,6,255,50,255)
    disp.update()
    log.info("LCD", "LCD IS finished!")
    sys.wait(1000)
    sys.publish("START_DONE")
end)

local cnt = 0
sys.subscribe("KEY_EVENT", function(k, e)
    if k == "C" and e then
        collectgarbage("collect")
        cnt = cnt + 1
        -- log.info("LCD","cnt=",cnt)
        if 0 == cnt % 2 then
            disp.clear()
            disp.putimage("/lua/3color.png", 0, 0)
            disp.update()
            log.info("LCD", "画面=", 0)
        end
        if 1 == cnt % 2 then
            disp.clear()
            disp.putimage("/lua/head240.jpg", 0, 0)
            disp.update()
            log.info("LCD", "画面=", 1)
        end
        collectgarbage("collect")

    end
end)
